if (!app.user) {app.redirect('/admin/login.php')}
jQuery(function() {

	var li = $('#product-list li:first').clone();

	function getProductList() {
		var serverReturn = _get('/app/index.php?d=admin&c=product&m=get_product_list');
		return serverReturn.product_list;
	}

	function generateProductLi(product) {
		var liClone = li.clone();
		liClone.attr('product-id', product['product_id']);
		liClone.find('a').html(product['product_name']);
		if (product['state'] != 'pre_vote') {
			liClone.addClass('disabled');
		} else {
			liClone.removeClass('disabled');
		}
		return liClone;
	}

	function updateProductList() {
		$('#product-list').empty();
		var products = getProductList();
		for (var i in products) {
			$('#product-list').append( generateProductLi(products[i]) );
		}
	}

	function updateOrderList() {
		var orderLi = $('#order-list li:first').clone();
		$('#order-list').empty();
		// return;
		$('#product-list li').each(function(i, ele) {
			var orderLiClone = orderLi.clone();
			i++;
			if (i <= 9) {
				i = '0' + i.toString();
			}
			orderLiClone.find('.badge').html(i);
			if ($(ele).hasClass('disabled')) {
				orderLiClone.addClass('disabled');
				orderLiClone.find('.badge').removeClass('badge-info');
			} else {
				orderLiClone.removeClass('disabled');
				orderLiClone.find('.badge').addClass('badge-info');
			}
			$('#order-list').append(orderLiClone);
		});
	}

	updateProductList();
	updateOrderList();

	// jquery ui sortable
	$('#product-list').sortable({items: "li:not(.disabled)"});

	$('#product-list').bind('sortupdate', function(e, ui) {
		$("#sort-success").stop().fadeIn('fast');
		setTimeout(function() {
			$('#sort-success').stop().fadeOut('normal')
		}, 300);

		// console.log( $('#product-list') );
		var ids_order = [];
		$('#product-list li').each(function(i, ele){
			var id = $(ele).attr('product-id');
			ids_order.push(id);
			// console.log(id_order);
		});

		_post('/app/index.php?d=admin&c=product&m=set_products_order', 
			{products_id_order: ids_order});

	});

})